package io.renren.modules.app.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import io.renren.modules.quickService.constants.AccountStatus;
import io.renren.modules.quickService.constants.AuditStatus;
import io.renren.modules.quickService.dao.UserDao;
import io.renren.modules.quickService.entity.UserEntity;
import io.renren.modules.quickService.entity.UserExtraEntity;
import io.renren.modules.quickService.service.UserExtraService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("appUserService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private UserExtraService userExtraService;

    @Override
    public UserEntity queryByMobile(String mobile) {
        UserEntity userEntity = new UserEntity();
        userEntity.setMobile(mobile);
        return baseMapper.selectOne(userEntity);
    }

    @Override
    public long login(LoginForm form) {
        UserEntity user = queryByMobile(form.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
            throw new RRException("手机号或密码错误");
        }
        //账号已注销
        if (!AccountStatus.AVAILABLE.getKey().equals(user.getAccountStatus())) {
            throw new RRException("账号已注销");
        }
        //账号未审核
        UserExtraEntity userExtraEntity = userExtraService.queryUserExtraByMobile(user.getMobile());
        if (!AuditStatus.VERIFIED.getKey().equals(userExtraEntity.getAuditStatus())) {
            throw new RRException("账号" + AuditStatus.getValueByKey(userExtraEntity.getAuditStatus()));
        }
        return user.getUserId();
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        UserEntity userEntity = new UserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new EntityWrapper<UserEntity>().eq("user_id", userId).eq("password", password));
    }
}
